package com.steamedfish.auctioncloudadserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.steamedfish.auctioncloudadserver.entiry.AdMailEntity;
import com.steamedfish.auctioncloudadserver.entiry.AuctionRegisterEntity;
import com.steamedfish.auctioncloudadserver.entiry.UserEntity;
import com.steamedfish.auctioncloudadserver.mapper.AdMailMapper;
import com.steamedfish.auctioncloudadserver.mapper.UserMapper;
import com.steamedfish.auctioncloudadserver.model.AuctionItemModel;
import com.steamedfish.auctioncloudadserver.service.AdMailService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.steamedfish.auctioncloudadserver.service.elasticsearch.ElasticSearchService;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 高山福
 * @since 2021-04-02
 */
@Service
public class AdMailServiceImpl extends ServiceImpl<AdMailMapper, AdMailEntity> implements AdMailService {

    @Autowired
    private SimpleMailMessage simpleMailMessage;

    @Autowired
    private MailSender mailSender;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AdMailMapper adMailMapper;

    @Autowired
    private ElasticSearchService elasticSearchService;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    private Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * 尝试发送
     *
     * @param id
     * @return int
     */
    @Override
    public void sendMail(List<String> mails, String subjext, String context) {
        logger.info(subjext);
        simpleMailMessage.setText(context);
        String[] a = new String[mails.size()];
        a = mails.toArray(a);
        simpleMailMessage.setTo(a);
        simpleMailMessage.setSubject(subjext);
        //尝试发送
        try {
            mailSender.send(simpleMailMessage);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("发送邮件失败");
        }
    }


    //群发提醒新品上市，每天中午12:00和晚上16:00提醒商品信息
    @Override
    public void sendMailInterval() {
        //获取发送的内容
        Map<String, String> map = elasticSearchService.searchByKey();
        if (map.size() == 0) {
            return;
        }

        //获取邮箱地址
        List<String> mails = getMailAddress();


        //指定发送对象
        String[] a = new String[mails.size()];
        a = mails.toArray(a);
        simpleMailMessage.setTo(a);

        //创建发送内容
        String codeText = "新品上新，快来看看有没有您中意的小商品\n\n";
        for (Map.Entry<String, String> entry : map.entrySet()) {
            codeText = codeText + entry.getKey() + "：" + entry.getValue() + "\n\n";
        }
        simpleMailMessage.setText(codeText);

        //尝试发送
        try {
            mailSender.send(simpleMailMessage);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("发送邮件失败");
        }
    }


    @Override
    public void sendMailForNote(){
        Map<String, String> map = elasticSearchService.searchForNotify();
        if (map.size() == 0) {
            return;
        }

        List<String> mails = new ArrayList<>();

        //创建发送内容
        String codeText = "以下商品即将开始拍卖，请抓紧时间：\n\n";
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String[] list = entry.getValue().split(" | ");
            String value = list[0];
            codeText = codeText + entry.getKey() + "：" + value + "\n\n";
        }
        simpleMailMessage.setText(codeText);



        //获取邮箱地址
        mails = getMailAddressByMap(map);

        //指定发送对象
        String[] a = new String[mails.size()];
        a = mails.toArray(a);
        simpleMailMessage.setTo(a);


        //尝试发送
        try {
            mailSender.send(simpleMailMessage);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("发送邮件失败");
        }

    }


    //群发给关注人群提醒，按时参与拍卖
    @Scheduled(cron = "0/5 * * * * *")
    public void test() {
        System.out.println(LocalDateTime.now() + "你好");
    }


    //通知拍卖结果给卖家


    //通知拍卖结果给买家



    @Override
    public List<String> getMailAddress(){
        QueryWrapper q1 = new QueryWrapper();
        q1.isNotNull("mail");
        QueryWrapper q2 = new QueryWrapper();
        q2.isNotNull("mail");

        List<String> mails = new ArrayList<>();

        List<UserEntity> userEntities = userMapper.selectList(q1);
        for (int i = 0; i < userEntities.size(); i++) {
            mails.add(userEntities.get(i).getMail());
        }
        List<AdMailEntity> adMailEntities = adMailMapper.selectList(q2);
        for (int i = 0; i < adMailEntities.size(); i++) {
            mails.add(adMailEntities.get(i).getMail());
        }
        return mails;
    }

    @Override
    public String getAlertContext(AuctionItemModel auctionItemModel) {
        //创建发送内容
        String codeText = "您订阅的商品"+auctionItemModel.getName()+"将在"+auctionItemModel.getAuctionTime()+"开始拍卖，请按时参与拍卖哦\n\n";
        codeText = codeText + "点击地址跳转到拍卖页：" + elasticSearchService.getAuctionURL(auctionItemModel.getId()) + "\n\n";
        return codeText;
    }


    public List<String> getMailAddressByMap(Map<String, String> map) {
        List<String> list = new ArrayList<>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String[] value = entry.getValue().split(" | ");
            String itemId = value[2];
            NativeSearchQuery query = new NativeSearchQueryBuilder()
                    .withQuery(QueryBuilders.matchPhraseQuery("itemId", itemId))
                    .withSort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))
                    .build();
            SearchHits<AuctionRegisterEntity> searchHits = elasticsearchRestTemplate.search(query, AuctionRegisterEntity.class, IndexCoordinates.of("auction_register"));

            if (searchHits.isEmpty()) {
                return list;
            }
            String userId = searchHits.getSearchHit(0).getContent().getUserId();

            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("id", userId);
            queryWrapper.isNotNull("mail");
            UserEntity userEntity = userMapper.selectOne(queryWrapper);
            if (userEntity != null) {
                list.add(userEntity.getMail());
            }

        }
        return list;
    }



}
